package respository

import (
	"gitee.com/song-yao-shun/MQH/common"
	"gitee.com/song-yao-shun/MQH/model"
	"gorm.io/gorm"
	"log"
)

//定义接口和定义增删改查的方法
type IRestRepository interface {
	Create(name string)
	Update(category model.Category,name string)
	SelectById(Id int)
	DeleteById(Id int)
	List(pageNum int, pageSize int)
}

type CategoryRepository struct {
	DB *gorm.DB
}

func NewCategoryRepository() CategoryRepository {
	db := common.GetDB()
	//db.AutoMigrate(model.Category{})

	return CategoryRepository{DB:db}
}

func (c CategoryRepository) Create(name string) (*model.Category,error) {
	category := model.Category{
		Name:	name,
	}

	if err := c.DB.Create(&category).Error; err != nil {
		log.Printf("新增失败，错误信息为：%v",err)
		return nil, err
	}

	return &category, nil
}

func (c CategoryRepository) Update(category model.Category, name string) (*model.Category,error) {
	if err := c.DB.Model(&category).Update("name",name).Error; err != nil {
		return nil, err
	}

	return &category, nil
}

func (c CategoryRepository) SelectById(Id int) (*model.Category,error) {
	var category model.Category

	if err := c.DB.First(&category, Id).Error; err != nil {
		return nil, err
	}

	return &category, nil
}

func (c CategoryRepository) DeleteById(Id int) (rowsAffected int64) {
	rowsAffected = c.DB.Delete(model.Category{}, Id).RowsAffected
	if rowsAffected != 1 {
		log.Printf("数据删除失败，删除操作影响行数为：%v，删除的id为：%v",rowsAffected,Id)
	}

	return rowsAffected
}

func (c CategoryRepository) List(pageNum int, pageSize int)(categories []model.Category, total int64){
	c.DB.Order("created_at desc").Offset((pageNum -1) * pageSize).Limit(pageSize).Find(&categories)

	// 前端渲染分页需要知道的总数
	c.DB.Model(model.Category{}).Count(&total)

	return categories,total
}